<?php

class Skjb_Diff_Traditional
{
    protected $_leftLines = array();
    
    protected $_rightLines = array();
    
    protected $_diff = array();
    
    public function __construct($leftLines, $diff) 
    {
        $this->_leftLines = $leftLines;
        $this->_diff = $diff;
        
        $this->_parse();
    }
    
    protected function _parse()
    {
        //print_r($this->_leftLines);
        
        //print_r($this->_diff);
        
        $this->_rightLines = array();
        
        $leftPos = 0;

        $action = '';
        for ($i = 0; $i < count($this->_diff); $i++) {
            $diff = $this->_diff[$i];
            //echo $diff . '<br />';
            $firstChar = substr($diff, 0, 1);
            if ($firstChar == '<') {
                $leftPos++;
            } elseif ($firstChar == '>') {
                $line = substr($diff, 2);
                $this->_rightLines[] = $line;
            } else {
                $action = '';
                preg_match('/(\d+),?(\d+)?([acd])(\d+),?(\d+)?/', $diff, $matches);
                //print_r($matches);
                if ($matches[3] == 'a') { // Add
                    while ($leftPos < $matches[1]) {
                        //echo $leftPos . '<br />';
                        $this->_rightLines[] = $this->_leftLines[$leftPos];
                        $leftPos++;
                    }
                    $action = 'add';
                } elseif ($matches[3] == 'd') {
                    //print_r($matches);
                    while ($leftPos < $matches[1] - 1) {
                        $this->_rightLines[] = $this->_leftLines[$leftPos];
                        $leftPos++;
                    }
                    $leftPos++;
                    $action = 'delete';
                }
            }
        }
        while ($leftPos < count($this->_leftLines)) {
            $this->_rightLines[] = $this->_leftLines[$leftPos];
            $leftPos++;
        }
    }
    
    public function apply()
    {
        return $this->_rightLines;
    }
}